package limbo.xmlParse;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import limbo.beans.Book;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;

public class Dom4jParseService {

	@SuppressWarnings("unchecked")
	public List<Book> getBooks(InputStream inputStream) throws SAXException,
			DocumentException {

		List<Book> list = new ArrayList<Book>();
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(inputStream);

		Element rootElement = document.getRootElement();
		Book book = null;
		List<Element> bookElements = rootElement.elements("book");
		for (Element elm : bookElements) {
			book = new Book();
			book.setId(Integer.parseInt(elm.attributeValue("id")));
			List<Element> elements = elm.elements();
			for (Element element : elements) {
				if ("name".equals(element.getName())) {
					book.setName(element.getText());
				} else if ("price".equals(element.getName())) {
					book.setPrice(Float.parseFloat(element.getText()));
				}
			}
			list.add(book);
		}

		return list;
	}
}
